'use client'

import { useEffect } from 'react'
import { Toolbox } from '@/components/Toolbox'
import { ViewerArea } from '@/components/ViewerArea'
import { PerformanceDashboard } from '@/components/PerformanceDashboard'
import { useComponentPreloader } from '@/components/LazyComponents'
import { usePerformanceMonitor } from '@/utils/performance'
import { smartPreloader, dataPreloader, DataPreloadStrategy } from '@/utils/preloader'
import { api } from '@/lib/api'

export default function HomePage() {
  const { preloadCritical } = useComponentPreloader()
  const { startTiming } = usePerformanceMonitor()

  useEffect(() => {
    // 页面加载性能监控
    const endTiming = startTiming('homepage_load')

    // 预加载关键组件
    preloadCritical()

    // 预加载关键数据
    const preloadCriticalData = async () => {
      try {
        // 添加数据预加载任务
        dataPreloader.addPreloadTask({
          key: 'datasets_all',
          priority: 10,
          strategy: DataPreloadStrategy.IMMEDIATE,
          loader: () => api.getDatasets(),
          estimatedSize: 5120 // 5KB 估算
        })

        // 预加载前3个数据集的详细信息
        const datasets = await api.getDatasets()
        if (datasets && datasets.length > 0) {
          datasets.slice(0, 3).forEach((dataset, index) => {
            dataPreloader.addPreloadTask({
              key: `dataset_${dataset.id}`,
              priority: 8 - index,
              strategy: DataPreloadStrategy.ON_IDLE,
              loader: () => api.getDataset(dataset.id),
              dependencies: ['datasets_all'],
              estimatedSize: 1024
            })
          })
        }

        // 执行预加载
        await dataPreloader.executePreload()
      } catch (error) {
        console.warn('Failed to preload critical data:', error)
      }
    }

    preloadCriticalData()

    // 启用智能预加载
    smartPreloader.predictivePreload('/')

    // 页面加载完成
    const handleLoad = () => {
      endTiming()
    }

    if (document.readyState === 'complete') {
      handleLoad()
    } else {
      window.addEventListener('load', handleLoad)
    }

    return () => {
      window.removeEventListener('load', handleLoad)
    }
  }, [preloadCritical, startTiming])

  return (
    <>
      <div className="main-view flex flex-col lg:grid lg:grid-cols-12 h-full">
        {/* 工具箱区域 - 在小屏幕上显示在顶部，大屏幕上显示在左侧 */}
        <div className="lg:col-span-3 toolbox-container h-auto lg:h-full">
          <Toolbox />
        </div>
        {/* 查看器区域 - 在小屏幕上占据剩余空间，大屏幕上占据右侧 */}
        <div className="flex-1 lg:col-span-9 viewer-container">
          <ViewerArea />
        </div>
      </div>

      {/* 性能监控仪表板 - 仅在开发环境显示 */}
      {process.env.NODE_ENV === 'development' && <PerformanceDashboard />}
    </>
  )
}
